<?php
namespace park\modules\pay\controllers;


use common\models\ParkCurrentSpace;
use common\Utils;
use Yii;
use yii\helpers\ArrayHelper;
use yii\web\Controller;
use yii\web\Response;
use common\OrderProcess;
use common\models\OrderInfo;
/**
 * Site controller
 */
class WechatController extends Controller
{
    
    public function beforeAction($action)
    {
        $currentaction = $action->id;  
        $novalidactions = ['notify'];   
        if(in_array($currentaction,$novalidactions)) {  
            $this->enableCsrfValidation = false; 
        }   
        return parent::beforeAction($action); // TODO: Change the autogenerated stub
    }


    /**
     * Displays homepage.
     *
     * @return string
     */
    public function actionIndex($id = null)
    {
        $config = [
            'oauth' => [
                'scopes'   => ['snsapi_base'],
                'callback' => '/pay/wechat/?id='.$id,
            ],
        ];
        $app =  new \EasyWeChat\Foundation\Application( ArrayHelper::merge(Yii::$app->params['WECHAT'],$config));
        if(Utils::getParams("code") ==null)
        {
            if (empty($_SESSION['wechat_user'])) {
                $_SESSION['target_url'] = '/pay/wechat/?id='.$id;
                $app->oauth->redirect()->send();
            }
        }
        else
        {
            $user = $app->oauth->user();
            $attributes = [
                'trade_type'       => 'JSAPI', // JSAPI，NATIVE，APP...
                'body'             => 'LOK停车费',
                'detail'           => '停车费',
                'out_trade_no'     => str_replace("-","",$id) ,
                'total_fee'        => 1, // 单位：分
                'notify_url'       => 'http://park.loklok.cn/pay/wechat/notify', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
                'openid'           => $user->id, // trade_type=JSAPI，此参数必传，用户在商户appid下的唯一标识，
                // ...
            ];
            $order = new \EasyWeChat\Payment\Order($attributes);
            $result = $app->payment->prepare($order);
            if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
                $prepayId = $result->prepay_id;
                $config = $app->payment->configForJSSDKPayment($prepayId);
                $js = $app->js;

                return $this->render('index',
                    [
                        'js'=>$js,
                        'config'=>$config
                    ]
                );
            }
            else
            {
                Yii::$app->response->format = Response::FORMAT_JSON;
                $result["id"] = $id;
                $result["configs"] = Yii::$app->params['WECHAT'];
                return $result;
            }

        }

    }

    public function actionNotify()
    {    
        $app =  new \EasyWeChat\Foundation\Application( Yii::$app->params['WECHAT']);
        $response = $app->payment->handleNotify(function($notify, $successful){
            // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
            $order = OrderInfo::findOne(['id'=>$notify->out_trade_no]); 
            if (!$order) { // 如果订单不存在
                return 'Order not exist.'; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
            }
            // 如果订单存在
            // 检查订单是否已经更新过支付状态
            if ($order->status == 1) { // 假设订单字段“支付时间”不为空代表已经支付
                return true; // 已经支付成功了就不再更新了
            }
            // 用户是否支付成功
            if ($successful) {
                OrderProcess::setOrderStatus($order,1);
            } else { // 用户支付失败
                //$order->status = 0;
            }
            return true; // 返回处理完成
        });

        $response->send();

    }





}
